package com.springboot.base.springbootes.utils;

import com.alibaba.fastjson.JSON;
import com.springboot.base.springbootes.pojo.PageResult;
import com.springboot.base.springbootes.pojo.esHotelVo.HotelDoc;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Map;

/**
 * @author: 船长
 * @create: 2025-03-15 17:07
 **/

public class EsResponseUtil {
    /**
     * 抽取解析结果方法
     * @param response
     */
    public PageResult handleResponse(SearchResponse response) {
        // 解析结果
        SearchHits searchHit = response.getHits();
        // 查询总条数
        long total = searchHit.getTotalHits().value;
        // 查询的结果数组
        SearchHit[] hits = searchHit.getHits();
        ArrayList<HotelDoc> hotels = new ArrayList<>();
        for (SearchHit hit : hits){
            // 得到source文档信息
            String json = hit.getSourceAsString();
            // 反序列化
            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
            hotels.add(hotelDoc);
            // 获取高亮结果
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (!CollectionUtils.isEmpty(highlightFields)) {
                // 根据名字获取高亮结果
                HighlightField highlightField = highlightFields.get("name");
                if (highlightField != null){
                    // 获取高亮的值
                    String name = highlightField.getFragments()[0].string();
                    // 覆盖非高亮结果
                    hotelDoc.setName(name);
                    // 打印
                }
            }
            System.out.println(hotelDoc);
        }
        System.out.println("总条数：" + total);

        return new PageResult(total, hotels);
    }

}
